﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrusadeGmTool.Net;
using CrusadeGmTool.Diagnostics;
using System.Windows.Forms;
using CrusadeGmTool.Net.IO;
using System.Threading;

namespace CrusadeGmTool.Models
{
    public class Admin
    {
         Server _server;

        Logger _log;
        ServerInfo _serverInfo;
        event EventHandler ReceivedInfos;
        System.Threading.Timer timer;


        public NetworkContext Network
        {
            get
            {
                return _server.Network;
            }
        }
        public  ServerInfo serverInfos
        {
            get { return _serverInfo;}
        }

        public  Admin()
        {
            _log = new Logger("Admin");    
            _serverInfo = new ServerInfo();
        }

        public void InitNetwork()
        {
            _log.TraceFunction();

            Network.Register(0x01, "Compressed", null, true, null);
            Network.Register(0x02, "Login Response", 2, OnLoginResult);
            Network.Register(0x04, "Server Info", null, OnServerInfo);

        }

        void askForInfos(object dummy)
        {
            Network.Send(new ServerInfoRequestPacket());
                  
        }
        public void OnLoginResult(PacketReader reader)
        {
            timer = new System.Threading.Timer(new TimerCallback(askForInfos), null, 0, 1000);
        }

        public void OnServerInfo(PacketReader reader)
        {
            _serverInfo.Initialized = true;
            _serverInfo.ActiveAccountsCount = reader.ReadInt32();
            _serverInfo.BannedAccountsCount = reader.ReadInt32();
            _serverInfo.FirewalledIpCount = reader.ReadInt32();
            _serverInfo.OnlineCount = reader.ReadInt32();
            _serverInfo.MobileCount = reader.ReadInt32();
            _serverInfo.ScriptMobilesCount = reader.ReadInt32();
            _serverInfo.ItemsCount = reader.ReadInt32();
            _serverInfo.ScriptedItemsCount = reader.ReadInt32();
            _serverInfo.Uptime = TimeSpan.FromSeconds(reader.ReadUInt32());
            _serverInfo.MemoryUsage = reader.ReadUInt32();
            _serverInfo.DotNetVersion = reader.ReadString();
            _serverInfo.OSVersion = reader.ReadString();
            if (ReceivedInfos != null)
                ReceivedInfos(_serverInfo, null);
        }
    }
}
